#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using System.Collections;
using System.Xml;
using System;
using System.Collections.Generic;

namespace CchenSoft.Workflow.Loader
{
    public class SplitDescriptor : AbstractDescriptor, IValidatable
    {
        //~ Instance fields ////////////////////////////////////////////////////////

        protected List<ResultDescriptor> results = new List<ResultDescriptor>();

        //~ Constructors ///////////////////////////////////////////////////////////

        /**
         * @deprecated use {@link DescriptorFactory} instead
         */
        public SplitDescriptor()
        {
        }

        /**
         * @deprecated use {@link DescriptorFactory} instead
         */
        public SplitDescriptor(XmlElement split)
        {
            Init(split);
        }

        //~ Methods ////////////////////////////////////////////////////////////////

        public IList<ResultDescriptor> Results
        {
            get { return results; }
        }

        public void Validate()
        {
            ValidationHelper.Validate((ICollection<IValidatable>)results);
        }

        public override void WriteXML(XmlTextWriter writer, int indent)
        {
            XMLUtil.printIndent(writer, indent++);
            writer.WriteStartElement("split");
            writer.WriteAttributeString("id", Id.ToString());

            for (int i = 0; i < results.Count; i++)
            {
                ResultDescriptor result = (ResultDescriptor)results[i];
                result.WriteXML(writer, indent);
            }

            XMLUtil.printIndent(writer, --indent);
            writer.WriteEndElement(); // ("</split>");
        }

        private void Init(XmlElement split)
        {
            string id = XMLUtil.GetAttributeValue(split, "id");
            try
            {
                Id = (Convert.ToInt32(id));
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Invalid split id value " + id);
            }

            XmlNodeList uResults = split.SelectNodes("unconditional-result");

            for (int i = 0; i < uResults.Count; i++)
            {
                XmlElement result = (XmlElement)uResults[i];
                ResultDescriptor resultDescriptor = new ResultDescriptor(result);
                resultDescriptor.Parent = this;
                results.Add(resultDescriptor);
            }
        }
    }
}
